package org.helgoboss.terminal_commandlet

import org.helgoboss.commandlet._
import java.io.File
import org.helgoboss.terminal.Terminal
import org.helgoboss.shell.Shell
import org.helgoboss.launchlet.{LaunchletExecutionContext, Launchlet}

class TerminalCommandlet(terminal: Terminal, shell: Shell) extends Commandlet with Launchlet {
	val id = "org.helgoboss.terminal"
    
    val name = "Terminal"
    
	def execute(context: ExecutionContext) = {
        openTerminal(context.workingDirectory, context.arguments)
	}

    private def openTerminal(workingDir: File, arguments: Seq[String]) = {
        val absoluteFile = arguments.lift(0) orElse Some(".") match {
            case Some(p) =>
                val f = new File(p)
                val absoluteFile = if (f.isAbsolute) f else new File(workingDir, p)
                Some(if (absoluteFile.isDirectory) absoluteFile else absoluteFile.getParentFile)

            case None => None
        }
        terminal.open(innerCommandComponents = shell.getCommandComponentsForOpeningInteractiveShell(absoluteFile))
        0
    }
    
	def execute(context: LaunchletExecutionContext) = {
        context.workingDirectory match {
            case Some(d) =>
                openTerminal(d, context.arguments)
                
            case None => 
                terminal.open(innerCommandComponents = shell.getCommandComponentsForOpeningInteractiveShell())
                0
        }
	}
}